<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发起流程</span>
      </div>
      <el-col :span="18" :offset="3">
        <div class="form-conf" v-if="formOpen">
          <v-form-render v-if="formOpen" :form-json="formData" ref="vFormRef"></v-form-render>
          <div class="dialog-footer">
            <el-button type="info" icon="el-icon-circle-plus-outline" @click="submitForm('0')">暂存</el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submitForm('1')">提交</el-button>
          </div>
          <!-- <el-button type="primary" @click="submitForm">打印</el-button> -->
          <!-- <v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef"> -->
          <!-- </v-form-render> -->
          <!-- <el-button type="primary" @click="submitForm">Submit</el-button> -->
          <!-- <parser :key="new Date().getTime()" :form-conf="formData" @submit="submit" ref="parser" @getData="getData"/> -->
        </div>
      </el-col>
    </el-card>
  </div>
</template>

<script>
import { getProcessForm, startProcess,getProcessFormHold } from '@/api/workflow/process'
import { listForm, getForm, delForm, addForm, updateForm } from "@/api/workflow/form";
import { getInfo } from '@/api/login'
// import {mapGetters} from 'vuex'
import Parser from '@/utils/generator/parser'

export default {
  name: 'WorkStart',
  components: {
    Parser
  },

  data() {
    return {
      definitionId: null,
      deployId: null,
      formOpen: false,
      formData: {},
      validForm: false,
      validForm2: false,
      timer:''
    }
  },
  mounted() {
    // console.log(this.userInfo,"yonghu");
  },
  created() {
    this.initData();
  },
  computed: {
    _userInfo() {
        return this.$store.state.user.userInfo
      }
   },
  methods: {
    async initData() {
      this.deployId = this.$route.params && this.$route.params.deployId;
      this.definitionId = this.$route.query && this.$route.query.definitionId;
      const res = await getProcessForm({definitionId: this.definitionId,deployId: this.deployId})
      if (res.data) {
          console.log(res.data,'res.data');
          this.formData = res.data;
          this.formOpen = true
          this.timer = setTimeout(this.userInfo,500)
      }
        
    },
    userInfo() {
      console.log(this._userInfo, "5656");
      this.$refs.vFormRef.setFieldValue('orgName',this._userInfo.nickName)
      this.$refs.vFormRef.setFieldValue('deptName',this._userInfo.dept.deptName)
      this.$refs.vFormRef.setFieldValue('phonenumber',this._userInfo.phonenumber)
      this.$refs.vFormRef.setFieldValue('newDate',this.$moment().format('YYYY-MM-DD'))
      console.log(this.$refs.vFormRef,"900909");
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    // submit(data) {
    //   if (data && this.definitionId) {
    //     // 启动流程并将表单数据加入流程变量
    //     startProcess(this.definitionId, JSON.stringify(data.valData)).then(res => {
    //       this.$modal.msgSuccess(res.msg);
    //       this.$tab.closeOpenPage({
    //         path: '/work/own'
    //       })
    //     })
    //   }
    // },
    // 暂存表单
    submitAdd() {
      const Code = 'CODE_YW'
      // console.log(this.$refs.vFormRef.getFormData());
      let obj = this.$refs.vFormRef.getFormData(false)
      console.log(obj);
      //   .then(formData => {
        getProcessFormHold(this.definitionId, JSON.stringify(obj),Code).then(res => {
          console.log(res);
          if (res.code == 200) {
            this.$modal.msgSuccess('暂存成功');
              this.$tab.closeOpenPage({
                path: '/work/own'
              })
              }
            })
      // });
    },
    // 提交表单按钮
    submitForm(type) {
      const Code = 'CODE_YW'
      // 校验表单
      this.$refs['vFormRef'].validateForm((valid) => {
        // 获取切换框的值
        const val = this.$refs.vFormRef.getFieldValue('cut')
        // 判断是否有切换表单
        if (val.length !== 0) {
          console.log('切换');
          if (val == 1) {
            if (valid) {
              // 当前展示表单校验通过
              this.validForm = true
              // 赋值给切换框
              this.$refs.vFormRef.setFieldValue('cut', 2)
              // 再次校验当前表单
              this.$refs['vFormRef'].validateForm((validl) => {
                console.log(validl);
                if (validl) {
                  // 当前表单二校验通过
                  console.log("1");
                  this.validForm2 = true
                  this.cutForm(type)
                }
              })
            }
          } else if (val == 2) { 
            // 如果表单二展示
            if (valid) {
              // 校验通过
              this.validForm2 = true
              // 赋值给切换框
              // this.$nextTick(() => {
                this.$refs.vFormRef.setFieldValue('cut', 1)
              // })
              // 再次校验当前展示表单
              this.$refs['vFormRef'].validateForm((validlS) => {
                console.log(validlS,'kan');
                if (validlS) {
                // 校验通过
                console.log("2");
                this.validForm = true
                this.cutForm(type)
                }
              })
            }
          }
        } else {
          console.log('不切换');
          if (type == '1') {
            this.$refs.vFormRef.getFormData().then(formData => {
            console.log(formData);
            startProcess(this.definitionId, JSON.stringify(formData),Code).then(res => {
              console.log(res);
              this.$modal.msgSuccess(res.msg);
              this.$tab.closeOpenPage({
                path: '/work/own'
              })
            })
          })
          } else {
            this.$refs.vFormRef.getFormData().then(formData => {
            console.log(formData);
            getProcessFormHold(this.definitionId, JSON.stringify(formData),Code).then(res => {
              console.log(res);
              this.$modal.msgSuccess('暂存成功');
              this.$tab.closeOpenPage({
                path: '/work/own'
              })
            })
          })
          }
          
        }
      })
    },

    // 表单校验方法
    cutForm(type) {
      const Code = 'CODE_YW'
      console.log(this.validForm,this.validForm2,"通过");
      if (this.validForm && this.validForm2) {
        this.$refs.vFormRef.setFieldValue('cut', 1)
        if (type == '1') {
          this.$refs.vFormRef.getFormData().then(formData => {
            startProcess(this.definitionId, JSON.stringify(formData),Code).then(res => {
            console.log(res);
          this.$modal.msgSuccess(res.msg);
          this.$tab.closeOpenPage({
            path: '/work/own'
          })
        })
        }).catch(error => {
          // Form Validation failed
          this.$message.error(error)
        })
        } else {
          this.$refs.vFormRef.getFormData().then(formData => {
            console.log(formData);
            getProcessFormHold(this.definitionId, JSON.stringify(formData),Code).then(res => {
              console.log(res);
              this.$modal.msgSuccess('暂存成功');
              this.$tab.closeOpenPage({
                path: '/work/own'
              })
            })
          })
        }
          
        } else {
          
        }
    }
  },
  //销毁定时器，不然会一直存在
    beforeDestroy() {
      clearTimeout(this.timer);
    }

}
</script>

<style lang="scss" scoped>
.form-conf {
  margin: 15px auto;
  width: 80%;
  padding: 15px;
}
.dialog-footer {
  margin: 15px auto;
  text-align: center;
}
</style>
